<template>
  <div class="dashboard-container">
    <div class="app-container">
      <el-card shadow="never">
        <!-- 面包屑 -->
        <el-breadcrumb
          v-if="showDsp"
          class="board"
          separator-class="el-icon-arrow-right"
        >
          <el-breadcrumb-item>首页</el-breadcrumb-item>
          <el-breadcrumb-item>学科管理</el-breadcrumb-item>
          <el-breadcrumb-item>目录</el-breadcrumb-item>
        </el-breadcrumb>
        <el-form :inline="true" :model="page" class="demo-form-inline">
          <div>
            <el-form-item label="目录名称">
              <el-input v-model="page.directoryName"></el-input>
            </el-form-item>
            <el-form-item label="状态">
              <!-- <el-input v-model="page.user"></el-input> -->
              <el-select v-model="page.state" placeholder="请选择">
                <el-option label="启用" value="1"></el-option>
                <el-option label="禁用" value="0"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button @click="empty" plain>清除</el-button>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="search">搜索</el-button>
            </el-form-item>
          </div>

          <!-- 学科进入显示/隐藏按钮 -->
          <div>
            <el-button
              v-if="showDsp"
              icon="el-icon-back"
              type="text"
              @click="$router.back()"
              >返回学科</el-button
            >
            <el-button
              icon="el-icon-edit"
              @click="addOff()"
              type="success"
              class="el-button el-button--success el-button--small"
              size="small"
            >
              新增目录</el-button
            >
          </div>
        </el-form>

        <!-- 弹层 -->
        <el-dialog
          width="28%"
          :title="form.id ? '修改目录' : '新增目录'"
          :visible.sync="dialogFormVisible"
          @close="close"
        >
          <el-form :model="form">
            <el-form-item
              v-if="!showDsp"
              label="所属学科"
              :label-width="formLabelWidth"
            >
              <!-- 学科下拉框 -->
              <el-select v-model="form.subjectID" placeholder="请选择">
                <el-option
                  v-for="item in addName"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                >
                </el-option>
              </el-select>
              <!--  学科下拉框结束-->
            </el-form-item>
            <el-form-item label="目录名称" :label-width="formLabelWidth">
              <el-input
                v-model="form.directoryName"
                placeholder="请输入目录名称"
                size="normal"
              ></el-input>
            </el-form-item>
          </el-form>
          <div slot="footer" class="dialog-footer">
            <el-button @click="close">取 消</el-button>
            <el-button type="primary" @click="OK()">确 定</el-button>
          </div>
        </el-dialog>
        <!-- 提示 -->
        <el-alert
          v-if="alertText !== ''"
          :title="alertText"
          type="info"
          class="alert"
          :closable="false"
          show-icon
        ></el-alert>
        <el-table :data="tableData" style="width: 100%">
          <el-table-column type="index" label="序号" width="80px">
          </el-table-column>
          <el-table-column prop="subjectName" label="所属学科">
          </el-table-column>
          <el-table-column prop="directoryName" label="目录名称">
          </el-table-column>
          <el-table-column prop="username" label="创建者"> </el-table-column>
          <el-table-column prop="addDate" label="创建日期">
            <template #default="{ row }">
              {{ formatDate(row.timeOfEntry) }}
            </template>
          </el-table-column>
          <el-table-column prop="totals" label="面试题数量"> </el-table-column>
          <el-table-column prop="state" label="状态">
            <template #default="{ row }">
              {{ row.state === 0 ? "已禁用" : "已启用" }}
            </template>
          </el-table-column>
          <el-table-column label="操作" fixed="right" width="200">
            <template #default="{ row }">
              <el-button type="text" size="small" @click="cgeState(row)">
                {{ row.state === 1 ? "禁用" : "启用" }}
              </el-button>
              <el-button
                :disabled="row.state === 1 ? true : false"
                type="text"
                size="small"
                @click="updateList(row)"
              >
                修改
              </el-button>
              <el-button
                :disabled="row.state === 1 ? true : false"
                type="text"
                size="small"
                @click="removeList(row.id)"
              >
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>

        <!-- <div class="grid-content bg-purple"> -->
        <el-pagination
          style="margin-top: 20px"
          background
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="page.page"
          :total="total"
          :page-size="page.pagesize"
          :page-sizes="[5, 10, 20, 30]"
          layout=" ->, prev, pager, next, sizes, jumper"
        >
        </el-pagination>
        <!-- </div> -->
      </el-card>
    </div>
  </div>
</template>

<script>

import { list, remove, changeState, add, update } from '@/api/hmmm/directorys'
import { simple } from '@/api/hmmm/subjects'
import dayjs from 'dayjs'
export default {
  data () {
    return {
      // 控制返回学科按钮是否显示
      showDsp: false,
      rules: {
        subjectID: [{ required: true, message: '目录名称', trigger: ['blur', 'change'] }],
        directoryName: [{ required: true, message: '目录名称', trigger: ['blur', 'change'] }]
      },
      // 学科列表
      addName: [],
      total: 0,
      // 默认显示页
      currentPage: 1,
      del: [],
      alertText: '',
      dialogFormVisible: false,
      form: {
        // 学科ID
        subjectID: '',
        // 目录名称
        directoryName: ''
      },
      formLabelWidth: '100px',
      page: {
        page: 1,
        pagesize: 5,
        directoryName: '',
        state: null
      },
      tableData: []
    }
  },
  created () {
    console.log(this.$route.params)
    this.getList()
    this.getSubject()
  },
  watch: {
    $route: {
      // 一进入页面立即执行
      immediate: true,
      handler: function (newVal, oldVal) {
        console.log('路由变化', newVal)
        if (newVal.fullPath === '/subjects/directorys') {
          this.showDsp = false
        } else this.showDsp = true
      }
    }

  },

  methods: {

    // 学科进入显示/隐藏按钮
    // showDsp () {

    // },
    // 关闭弹层
    close () {
      this.form = {
        // 学科ID
        subjectID: '',
        // 目录名称
        directoryName: ''
      }
      this.dialogFormVisible = false
    },
    // 修改
    updateList (row) {
      this.dialogFormVisible = true
      console.log('点击修改获取数据：', row)
      this.form = JSON.parse(JSON.stringify(row))
    },
    // 新增/修改目录
    async OK () {
      if (this.form.id) {
        // 编辑
        await update(this.form)
        this.$message.success('修改成功！')
      } else {
        // 新增
        const res = await add(this.form)
        console.log('11', res)
        this.$message.success('新增成功！')
      }
      this.close()
      this.getList()
    },
    // 获取学科列表
    async getSubject () {
      const { data } = await simple()
      console.log('获取学科列表:', data)
      this.addName = data
      console.log('123', this.addName)
    },
    // 渲染弹框选项
    addOff () {
      this.dialogFormVisible = true
    },
    // 启用禁用 取反
    async cgeState (val) {
      if (val.state === 1) {
        await changeState({ id: val.id, state: 0 })
      } else { await changeState({ id: val.id, state: 1 }) }
      this.getList()
    },
    // 分页
    handleSizeChange (val) {
      this.page.pagesize = val
      this.getList()
    },
    handleCurrentChange (vall) {
      this.page.page = vall
      this.getList()
    },
    // 搜索
    search () {
      this.getList()
      // this.page.directoryName = ''
    },
    // 删除数据
    async removeList (id) {
      this.del.id = id
      this.$confirm('此操作将永久删除?' + ',?是否继续?', '提示', {
        type: 'warning'
      }).then(async () => {
        try {
          await remove(this.del)
          // 解决末页删除最后一条数据显示空白页的Bug
          const newPage = Math.ceil((this.total - 1) / this.page.pagesize)
          // 页码 > 0 (默认页码最小是1)
          if (newPage > 0) {
            // 纠正页码
            this.page.page = this.page.page > newPage ? newPage : this.page.page
          }

          this.getList()
          this.$message.success('成功删除' + '!')
        } catch (err) {
          this.$message.error('删除失败!')
        }
      }).catch(() => {
        this.$message.info('已取消操作!')
      })
    },

    // 清空按钮
    empty () {
      this.page.directoryName = ''
      this.page.state = ''
    },
    // 格式化状态
    // format (state) {
    //   // console.log(state)
    //   const map = { 1: '已启用', 0: '已禁用' }
    //   return map[state]
    // },
    // 时间格式化
    formatDate (value, str = 'YYYY-MM-DD') {
      return dayjs(value).format(str)
    },
    // 获取数据
    async getList () {
      const res = await list(this.page)
      console.log('获取的目录信息：', res)
      this.total = res.data.counts
      this.tableData = res.data.items
      this.alertText = `数据一共 ${res.data.counts} 条`
    }

  }
}

</script>

<style lang="scss" scoped>
.app-container {
  padding: 10px;
}
.demo-form-inline {
  display: flex;
  justify-content: space-between;
}
.grid-content {
  margin-top: 20px;
}
.el-select {
  width: 100%;
}
</style>
